from PyQt4 import QtCore
from PyQt4.QtGui import *
import sys
from PyQt4.QtCore import SIGNAL

qApp = QApplication(sys.argv)

def ensureSingleApp(name):
    global mem

    mem = QtCore.QSharedMemory("%s Shared Memory" % name)
    if not mem.create(64) and mem.error() == QtCore.QSharedMemory.AlreadyExists:
        print("%s is already running." % name)
        sys.exit(0)

def getValue(parent, title, message, type=str):
    dlg = QDialog(parent)
    layout = QGridLayout()

    dlg.setWindowTitle(title)

    # message
    layout.addWidget(QLabel(message), 0, 0)

    # value
    value = QLineEdit()
    layout.addWidget(value, 0, 1)

    # buttons
    btnBox = QDialogButtonBox()
    btnBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok)

    def onAccept():
        try:
            type(value.text())
            dlg.accept()
        except:
            pass

    dlg.connect(btnBox, SIGNAL("accepted()"), onAccept)
    dlg.connect(btnBox, SIGNAL("rejected()"), dlg.reject)
    layout.addWidget(btnBox, 1, 1, 1, 2)
    
    dlg.setLayout(layout)

    if QDialog.Accepted != dlg.exec_():
        return None

    try:
        return type(value.text())
    except:
        return None